package ru.passivemoney.manage.job;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JobsRunner {
	
	private static final Logger logger = LoggerFactory.getLogger(JobsRunner.class);
	
	private final static List<Job> JOBS = new ArrayList<Job>();
	
	private static class JobThread implements Runnable{

		private Job job;
		
		public JobThread(Job job) {
			super();
			this.job = job;
		}

		@Override
		public void run() {
			job.execute();
		}
		
	}
	
	public static final void runJobs(){
		synchronized(JOBS){
			if(JOBS.size() == 0) return;
			
			logger.info("JOBS size - {}. Start jobs." ,JOBS.size());
			
			for (Iterator<Job> iterator = JOBS.iterator(); iterator.hasNext();) {
				new Thread(new JobThread(iterator.next())).start();
				iterator.remove();
			}
		}
	}
	
	public static final void putJob(Job job){
		synchronized(JOBS){
			logger.info("JOBS size - {}. Adding new Job with id - {}." , JOBS.size(), job.getId());
			JOBS.add(job);
		}
	}
	
}
